package com.fan.admin.controller;

import com.fan.admin.service.ClaInfoService;
import com.fan.admin.service.CourseRelationService;
import com.fan.admin.service.CourseService;
import com.fan.admin.service.StudentService;
import com.fan.admin.util.LocalCache;
import com.fan.commons.pojo.*;
import com.fan.commons.util.JsonResult;
import com.fan.commons.util.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fan
 * @date 2021/2/28
 */
@RestController
public class StudentController {

	@Autowired
	private StudentService studentService;

	@Autowired
	private ClaInfoService claInfoService;

	@Autowired
	private CourseRelationService courseRelationService;

	@Autowired
	private CourseService courseService;

	@Autowired
	private LocalCache localCache;

	@PostMapping("/student/add")
	public JsonResult addTeacher(Student student) {
		// student 在添加之前要完善 student 中的信息，并且后端要完成验证
		List<ClaInfo> claInfos = claInfoService.queryCalInfo(new ClaInfo().setClaId(student.getClaId()));
		if (claInfos.size() != 1) {
			return JsonResult.failure();
		}
		student = setStudentContent(student, claInfos.get(0));
		student.setPassword(student.getName());
		int code = studentService.insertStudent(student);
		if (code == 1) {
			return JsonResult.success(null);
		}
		return JsonResult.failure();
	}

	@GetMapping("/student/list")
	public JsonResult studentList(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer pageSize) {
		// 分页查询
		PageHelper.startPage(page, pageSize);
		List<Student> students = studentService.queryStudent(null);
		for (Student student : students) {
			student.setCollegeId(localCache.getCollegeInfoCache(student.getCollegeId()).getName());
			student.setSystemId(localCache.getSystemInfoCache(student.getSystemId()).getName());
		}
		PageInfo<Student> pageInfo = new PageInfo<>(students);
		PageUtil pageUtil = new PageUtil(pageInfo.getPageNum(), pageInfo.getPageSize(), students, pageInfo.getTotal());
		return JsonResult.success(pageUtil);
	}

	@GetMapping("/student/query/{id}")
	public JsonResult teacherQuery(@PathVariable Integer id) {
		List<Student> students = studentService.queryStudent(new Student().setId(id));
		if (students.size() == 1) {
			return JsonResult.success(students.get(0));
		}
		return JsonResult.failure();
	}

	@PutMapping("/student/update")
	public JsonResult teacherUpdate(Student student) {
		String claId = student.getClaId();
		// 班级重置，需要重新获取学号，院系
		if (!student.getStudentId().contains(claId)) {
			List<ClaInfo> claInfos = claInfoService.queryCalInfo(new ClaInfo().setClaId(claId));
			if (claInfos.size() != 1) {
				return JsonResult.failure();
			}
			student = setStudentContent(student, claInfos.get(0));
		}
		int code = studentService.updateStudent(student);
		if (code == 1) {
			return JsonResult.success(null);
		}
		return JsonResult.failure();
	}

	@GetMapping("/student/delete")
	public JsonResult studentDeleteById(@RequestParam Integer id) {
		int code = studentService.deleteStudent(id);
		if (code == 1) {
			return JsonResult.success(null);
		}
		return JsonResult.failure();
	}

	@GetMapping("/student/courses")
	public JsonResult getStudentCourse(Student student) {
		student = studentService.queryStudentById(2);
		List<Course> courses = new ArrayList<>();
		courses.addAll(courseRelationService.queryStudentCourse(new CourseRelation().setRelationId(student.getClaId())));
		courses.addAll(courseRelationService.queryStudentCourse(new CourseRelation().setRelationId(student.getStudentId())));
		PageUtil pageUtil = new PageUtil(1, 1, courses, (long) courses.size());
		return JsonResult.success(pageUtil);
	}

	@GetMapping("/student/choose/list")
	public JsonResult getStudentChoose(Student student, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer pageSize) {
		PageHelper.startPage(page, pageSize);
		List<Course> courses = courseRelationService.queryStudentChooseCourse("1720331");
		PageInfo<Course> pageInfo = new PageInfo<>(courses);
		PageUtil pageUtil = new PageUtil(page, pageSize, courses, pageInfo.getTotal());
		return JsonResult.success(pageUtil);
	}

	@Transactional(rollbackFor = RuntimeException.class)
	@PutMapping("/student/course/choose/{id}")
	public JsonResult studentChooseCourse(@PathVariable Integer id) {
		Course course = courseService.queryCourseById(id);
		course.setRestNumber(course.getRestNumber() - 1);
		int code1 = courseService.updateCourse(course);
		int code2 = courseRelationService.insertCourseRelation
				(new CourseRelation(null, course.getCourseId(), "1720331", 1, "" + System.currentTimeMillis()));
		if (code1 != 1 || code2 != 1) {
			throw new RuntimeException("修改失败！");
		}
		return JsonResult.success(null);
	}


	@GetMapping("/student/choose/courses")
	public JsonResult studentChooseCourse(HttpServletRequest request) {
		List<Course> courses = courseRelationService.queryStudentCourse(new CourseRelation().setRelationId("1720331"));
		PageUtil pageUtil = new PageUtil(1, 1, courses, (long) courses.size());
		return JsonResult.success(pageUtil);
	}

	@Transactional(rollbackFor = RuntimeException.class)
	@PutMapping("/student/course/drop/{id}")
	public JsonResult studentChooseDrop(HttpServletRequest request, @PathVariable Integer id) {
		Course course = courseService.queryCourseById(id);
		course.setRestNumber(course.getRestNumber() + 1);
		int code1 = courseService.updateCourse(course);
		int code2 = courseRelationService.deleteRelationActive(new CourseRelation().setCourseId(course.getCourseId()).setRelationId("1720331"));
		if (code1 != 1 || code2 != 1) {
			throw new RuntimeException("修改失败！");
		}
		return JsonResult.success(null);
	}

	@GetMapping("/student/scores")
	public JsonResult studentScores(HttpServletRequest request) {
		List<Course> courses = studentService.studentScore("1720331");
		PageUtil pageUtil = new PageUtil(1, 1, courses, (long) courses.size());
		return JsonResult.success(pageUtil);
	}


	public Student setStudentContent(Student student, ClaInfo claInfo) {
		String claId = claInfo.getClaId();
		String studentId = studentService.getStudentId(claId);
		int newId = Integer.parseInt(studentId.substring(5, 7));
		newId = newId + 1;
		// 重新获取学号
		if (newId < 10) {
			student.setStudentId(claId + "0" + newId);
		} else {
			student.setStudentId(claId + newId);
		}
		// 设置院系
		SystemInfo systemInfo = localCache.getSystemInfoCache(claInfo.getSystemId());
		student.setSystemId(systemInfo.getSystemId());
		student.setCollegeId(systemInfo.getCollegeId());
		return student;
	}
}
